package cn.toma.service.impl.sys;

import cn.toma.core.AbstractService;
import cn.toma.dao.sys.DictMapper;
import cn.toma.model.sys.Dict;
import cn.toma.service.sys.DictService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service("dictService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictServiceImpl extends AbstractService<Dict> implements DictService
{

	@Resource
	private DictMapper dictMapper;

	@Override
	public List<Dict> findDicts(Dict dict)
	{
		try {
			Weekend<Dict> weekend = new Weekend<>(Dict.class);
			WeekendCriteria<Dict, Object> weekendCriteria = weekend.weekendCriteria();
			if (StringUtils.isNotBlank(dict.getKeyy())) {
				weekendCriteria.andEqualTo(Dict::getKeyy, dict.getKeyy());
			}
			if (StringUtils.isNotBlank(dict.getValuee())) {
				weekendCriteria.andEqualTo(Dict::getValuee, dict.getValuee());
			}
			if (StringUtils.isNotBlank(dict.getTableName())) {
				weekendCriteria.andLike(Dict::getTableName, "%" + dict.getTableName() + "%");
			}
			if (StringUtils.isNotBlank(dict.getFieldName())) {
				weekendCriteria.andEqualTo(Dict::getFieldName, dict.getFieldName());
			}
			return dictMapper.selectByCondition(weekend);
		} catch (Exception e) {
			log.error("获取字典信息失败", e);
			return null;
		}
	}

	/**
	 * 根据字典名称获取字典列表
	 *
	 * @param fieldName 字典名称
	 * @return
	 */
	@Override
	public List<Dict> findFieldName(String fieldName)
	{
		try {
			Weekend<Dict> weekend = new Weekend<>(Dict.class);
			WeekendCriteria<Dict, Object> weekendCriteria = weekend.weekendCriteria();
			if (StringUtils.isNotBlank(fieldName)) {
				weekendCriteria.andEqualTo(Dict::getFieldName, fieldName);
				return dictMapper.selectByCondition(weekend);
			}
		} catch (Exception e) {
			log.error("获取字典信息失败", e);

		}
		return null;
	}

	@Override
	@Transactional
	public void createDict(Dict dict)
	{
		this.save(dict);
	}

	@Override
	@Transactional
	public void updateDict(Dict dict)
	{
		this.dictMapper.updateByPrimaryKeySelective(dict);
	}

	@Override
	@Transactional
	public void deleteDicts(String[] dictIds)
	{
		List<String> list = Arrays.asList(dictIds);
		list.forEach(item ->
		{
			this.dictMapper.deleteByPrimaryKey(item);
		});

	}
}
